<?php

namespace System;

use System\Entity\Response;

class FrontController {

    private $router;

    public function __constructor() {
        
    }

    public function getRequestedURL() {
        return $_SERVER["REQUEST_URI"];
    }

    private function toRoute($object) {
        $route = Factory::create("Route");

        if (array_key_exists("urlPattern", $object)) {
            $pattern = $object["urlPattern"];
            if (!is_array($pattern)) return false;
            foreach($pattern as $component) {
                if (!is_string($component)) return false;
            }
            $route->setUrlPattern($object["urlPattern"]);
        } else return false;

        if (array_key_exists("controllerPath", $object))
            $route->setControllerPath($object["controllerPath"]);
        if (array_key_exists("controller", $object))
            $route->setController($object["controller"]);
        if (array_key_exists("entryAction", $object))
            $route->setEntryAction($object["entryAction"]);
        if (array_key_exists("action", $object))
            $route->setAction($object["action"]);
        if (array_key_exists("userGroups", $object))
            $route->setUserGroups($object["userGroups"]);
        return $route;
    }

    private function loadRouter() {
        $this->router = Factory::create("Router");

        $objects = ConfigLoader::getConfig("routes");

        if ($objects === NULL or !is_array($objects)) return false;

        foreach ($objects as $object) {
            $route = $this->toRoute($object);
            if ($route === false) return false;
            $this->router->addRoute($route);
        }
        return true;
    }

    public function run() {
        if (!$this->loadRouter()) {
            return new Response("HTML", "Cannot load Routes.json (missing file or wrong syntax).");
        }

        $this->router->setUrl($this->getRequestedURL());
        $route = $this->router->getRoute();
        if ($route === false) 
            return new Response("HTTP/1.0 404 Not Found", "404 Not found: You must have gone the wrong way, little kittie.");

        $parameter = $this->router->getParameter();
        $pageLoader = Factory::create("PageLoader");
        $pageLoader->setGetData($parameter);
        $pageLoader->setPostData($_POST);
        $pageLoader->setRoute($route);

        $response = $pageLoader->load();
        return $response;
    }
}